import json
import traceback
from datetime import datetime


class ParkingObject:
    """ 一个车位的类 """

    def __init__(self, name, top_left_location, bottom_right_location):
        self.name = name if name else "unknown"
        self.x1 = float(top_left_location[0])
        self.y1 = float(top_left_location[1])
        self.x2 = float(bottom_right_location[0])
        self.y2 = float(bottom_right_location[1])

    def __str__(self):
        return "停车位是{},\tx1:{},\ty1:{},\tx2{},\ty2{}".format(self.name, self.x1, self.y1, self.x2, self.y2)

    def contact_ratio(self, x1, y1, x2, y2, threshold=0.75):
        x1, y1, x2, y2 = map(float, [x1, y1, x2, y2])
        """ 计算与停车位接触的比例, 大于阈值认为改车位停有车辆 """
        # 停车位面积
        parking_area = (self.x2 - self.x1) * (self.y2 - self.y1)
        # 车辆检测框与停车位接触的面积
        contact_area = max(0, min(x2, self.x2) - max(x1, self.x1)) * \
                       max(0, min(y2, self.y2) - max(y1, self.y1))
        return contact_area / parking_area > threshold if contact_area > 0 else False

    def serialize(self):
        # 序列化成字典
        return {
            'name': self.name,
            'top_left': [self.x1, self.y1],
            'bottom_right': [self.x2, self.y2],
            'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }




def load_config(config_path="parking_detect/parking.json"):
    """ 加载配置文件，返回一个列表 """
    res = []
    try:
        with open(config_path, 'r') as f:
            data = json.loads(f.read())
            for i in data:
                res.append(ParkingObject(**i))
    except Exception as e:
        traceback.print_exc()
        print("初始化配置文件失败")
    return res
